package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequiredLogin;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
public class CheckLoginInterceptor implements HandlerInterceptor{
    //登录控制检测
    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        UserInfo user=null;
        //判断是否贴有注解
        if(handler instanceof HandlerMethod){
            HandlerMethod hm = (HandlerMethod) handler;
            //先获取到他的token
            String tonken = CookieUtil.getTonken(request, response);
            //在获取value
            user = userInfoRedisService.getUserByToken(tonken);
            if (hm.hasMethodAnnotation(RequiredLogin.class)){
                //登录检查
                if(user == null){
                    //然后通过token的值去拿到这个对象,如果这个对象是空的,就重定向到登录界面就行了,然后不让它通过
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        request.getSession().setAttribute("userInfo",user);
        return true;
    }
}
